package cn.com.twoke.game.client.games.framework.core;

import cn.com.twoke.game.client.GameClientManager;
import cn.com.twoke.game.client.cache.ClientCacheManager;
import cn.com.twoke.game.client.games.GameConfig;
import cn.com.twoke.game.client.games.gomoku.constants.GomokuGameConstant;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.awt.event.WindowListener;
import java.util.function.Consumer;

/**
 * 游戏窗口
 */
public class GameWindow extends WindowAdapter {
	
	private final JFrame frame;
	private final Game game;
	
	public GameWindow(Consumer<JFrame> consumer, Game game, String title) {
		this.frame = new JFrame();
		frame.setTitle(title);
//		设置默认关闭操作
		frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		consumer.accept(frame);
//		不允许变动窗口大小
		frame.setResizable(false);
		frame.pack();
//      设置显示位置到屏幕中间,必须在pack后面设置
		frame.setLocationRelativeTo(null);
//		设置窗口显示
		frame.addWindowListener(this);
		this.game = game;
	}

	public void open() {
		frame.setVisible(true);
	}

	public void close() {
		frame.dispose();
	}

	@Override
	public void windowClosing(WindowEvent e) {
		if (ClientCacheManager.INSTANCE.isLogin()) {
			int userOption = JOptionPane.showConfirmDialog(frame,
					"确认退出登录吗？","提示", JOptionPane.YES_NO_OPTION);
			if (userOption == JOptionPane.YES_OPTION) {
				if (this.game.isNetwork()) {
					GameClientManager.INSTANCE.stopGame(
							this.game.getId(),
							this.game.getRoomId(),
							this.game.getPlayerName(),
							false
					);
				}
				GameClientManager.INSTANCE.logout(ClientCacheManager.INSTANCE.getUsername());
			}
		} else {
			System.exit(0);
		}
	}

	public JFrame getWindow() {
		return frame;
	}
}
